package com.jianan.mis.service;

import static com.jianan.mis.util.MD5.MD5Encode;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.jianan.mis.data.cache.GroupCache;
import com.jianan.mis.data.dao.EmployeeDao;
import com.jianan.mis.data.domain.Employee;
import com.jianan.mis.data.domain.Group;

public class EmployeeServiceImpl implements EmployeeService {

	private EmployeeDao employeeDao;
	
	private void encryptPassword(Employee employee) {
		if (employee.getPassword().length() <= 10) {
			String encryptedPassword = MD5Encode(employee.getPassword());
			employee.setPassword(encryptedPassword);
		}
	}
	
	private void reloadGroups(Employee employee) {
		Set<Group> oldGroups = employee.getGroups();
		Set<Group> newGroups = new HashSet<Group>();
		for(Group group : oldGroups) {
			Group newGroup = GroupCache.getInstance().findByName(group.getName());
			newGroups.add(newGroup);
		}
		employee.setGroups(newGroups);
	}

	public void save(Employee employee) {
		reloadGroups(employee);
		encryptPassword(employee);
		employeeDao.save(employee);
	}

	public void update(Employee employee) {
		reloadGroups(employee);
		encryptPassword(employee);
		employeeDao.saveOrUpdate(employee);
	}

	public void remove(Employee employee) {
		employee.setGroups(null);
		employeeDao.remove(employee);
	}
	
	public List<Employee> getAll() {
		return employeeDao.getAll(Employee.class);
	}

	public Employee findByName(String name) {
		return employeeDao.findUniqueBy(Employee.class, "Name", name);
	}

	public Employee findByUsername(String username) {
		return employeeDao.findUniqueBy(Employee.class, "Username", username);
	}

	public void setEmployeeDao(EmployeeDao employeeDao) {
		this.employeeDao = employeeDao;
	}

}
